package com.example.partner.activity.my;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.example.partner.R;
import com.example.partner.activity.team.CreateTeamActivity;
import com.example.partner.activity.home.InterestActivity;
import com.example.partner.activity.team.JoinTeamActivity;
import com.example.partner.activity.home.LoginActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.databinding.FragmentIndividualBinding;
import com.example.partner.service.FollowService;
import com.example.partner.service.TeamService;
import com.example.partner.service.UserService;

;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class IndividualFragment extends Fragment implements View.OnClickListener {
    final String TAG = "IndividualFragment";

    private FragmentIndividualBinding binding;
    RelativeLayout person_btn, interest_btn, joinTeam_btn, createTeam_btn;
    ImageView imageView;
    TextView usernameTextView, interestCount, joinCount;
    Button logoutButton;
    private UserService userService;
    private TeamService teamService;
    private FollowService followService;
    Long loginUserId;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        IndividualViewModel individualViewModel =
                new ViewModelProvider(this).get(IndividualViewModel.class);

        binding = FragmentIndividualBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        person_btn = binding.personBtn;
        interest_btn = binding.interestBtn;
        joinTeam_btn = binding.joinTeamBtn;
        createTeam_btn = binding.createTeamBtn;
        imageView = binding.appImg;
        usernameTextView = binding.name;
        logoutButton = binding.logout;
        interestCount = binding.interestCount;
        joinCount = binding.joinCount;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        userService = retrofit.create(UserService.class);
        teamService = retrofit.create(TeamService.class);
        followService = retrofit.create(FollowService.class);
        if (getActivity() != null) {
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
            loginUserId = sharedPreferences.getLong("userId", -1);
            String username = sharedPreferences.getString("username", "defaultUsername");
            String avatar = sharedPreferences.getString("avatar", "");
            usernameTextView.setText(username);
            Glide.with(this)
                    .load(avatar)
                    .override(100, 100)
                    .into(imageView);

        }
        countMyFollows(loginUserId);
        countMyJoin(loginUserId);
        person_btn.setOnClickListener(this::onClick);
        interest_btn.setOnClickListener(this::onClick);
        joinTeam_btn.setOnClickListener(this::onClick);
        createTeam_btn.setOnClickListener(this::onClick);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),LoginActivity.class);
                startActivity(intent);
            }
        });
        logoutButton.setOnClickListener(view -> userService.logout().enqueue(new Callback<BaseResponse<Integer>>() {
            @Override
            public void onResponse(Call<BaseResponse<Integer>> call, Response<BaseResponse<Integer>> response) {
                BaseResponse<Integer> responseBody = response.body();
                Integer userId = responseBody.data;
                if (responseBody != null) {
                    if (response.isSuccessful()) {

                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        // 基于responseBody进行进一步处理
                    } else {
                        // 处理错误情况
                    }
                }

            }


            @Override
            public void onFailure(Call<BaseResponse<Integer>> call, Throwable t) {
                // 网络错误处理
                Log.e(TAG, "post回调失败：" + t.getMessage() + "," + t.toString());
                Toast.makeText(getContext(), t.getMessage() + "post回调失败", Toast.LENGTH_SHORT).show();
            }
        }));
        return root;
    }

    private void countMyJoin(Long loginUserId) {
        teamService.countMyJoinTeams(loginUserId).enqueue(new Callback<BaseResponse<Integer>>() {
            @Override
            public void onResponse(Call<BaseResponse<Integer>> call, Response<BaseResponse<Integer>> response) {
                if (getActivity() == null) return;

                getActivity().runOnUiThread(() -> {
                    if (response.isSuccessful() && response.body() != null) {
                        Integer count = response.body().getData();
                        joinCount.setText(String.valueOf(count)); // 确保这是字符串
                        // 更新UI或处理数据
                    } else {
                        // 处理错误情况
                        Toast.makeText(getContext(), "请求错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFailure(Call<BaseResponse<Integer>> call, Throwable t) {
                if (getActivity() == null) return;

                getActivity().runOnUiThread(() -> {
                    // 网络错误处理
                    t.printStackTrace();
                    Toast.makeText(getContext(), "网络错误", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void countMyFollows(Long loginUserId) {
        followService.countMyFollow(loginUserId).enqueue(new Callback<BaseResponse<Integer>>() {
            @Override
            public void onResponse(Call<BaseResponse<Integer>> call, Response<BaseResponse<Integer>> response) {
                if (getActivity() == null) return;

                getActivity().runOnUiThread(() -> {
                    if (response.isSuccessful() && response.body() != null) {
                        Integer count = response.body().getData();
                        interestCount.setText(String.valueOf(count)); // 确保这是字符串
                        // 更新UI或处理数据
                    } else {
                        // 处理错误情况
                        Toast.makeText(getContext(), "请求错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFailure(Call<BaseResponse<Integer>> call, Throwable t) {
                if (getActivity() == null) return;

                getActivity().runOnUiThread(() -> {
                    // 网络错误处理
                    t.printStackTrace();
                    Toast.makeText(getContext(), "网络错误", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }




    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        int selectedId  = view.getId();
        if (selectedId == R.id.person_btn){
            Intent intent1 = new Intent(getContext(), PersonDetailActivity.class);
            startActivity(intent1);

        } else if (selectedId == R.id.interest_btn) {
            Intent intent2 = new Intent(getContext(), InterestActivity.class);
            startActivity(intent2);
        } else if (selectedId == R.id.joinTeam_btn) {
            Intent intent3 = new Intent(getContext(), JoinTeamActivity.class);
            startActivity(intent3);
        }else if (selectedId == R.id.createTeam_btn){
            Intent intent4 = new Intent(getContext(), CreateTeamActivity.class);
            startActivity(intent4);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在这里刷新数据
        if (getActivity() != null) {
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
            String username = sharedPreferences.getString("username", "defaultUsername");
            // 更新UI元素
            usernameTextView.setText(username);
            // 如有需要，可以在这里添加其他数据的更新逻辑
        }
    }

}